<?php

namespace app\common\dao\system;

use app\common\model\system\SystemGroupData as model;
use app\common\dao\BaseDao;
use think\db\BaseQuery;

class SystemGroupDataDao extends BaseDao
{
    /**
    * 设置模型
    * @return model
    */
    protected function getModel(): string
    {
        return model::class;
    }

    public function getGroupDataWhere($type, $groupId): BaseQuery
    {
        return ($this->getModel())::getDB()->withAttr('value', function ($val) {
            return json_decode($val, true);
        })->where('type', $type)->where('group_id', $groupId)->order('sort DESC');
    }


    public function getGroupData($type, $groupId, ?int $page = null, ?int $limit = 10)
    {
        $query =  ($this->getModel())::getDB()->where('type', $type)->where('group_id', $groupId)->where('status', 1)->order('sort DESC');
        if (!is_null($page)) $query->page($page, $limit);
        $groupData = [];
        foreach ($query->column('value') as $k => $v) {
            $groupData[] = json_decode($v, true);
        }
        return $groupData;
    }

    public function getGroupDataId($type, $groupId, ?int $page = null, ?int $limit = 10)
    {
        $query =  ($this->getModel())::getDB()->where('type', $type)->where('group_id', $groupId)->where('status', 1)->order('sort DESC');
        if (!is_null($page)) $query->page($page, $limit);
        $groupData = [];
        foreach ($query->column('value', 'group_data_id') as $k => $v) {
            $groupData[] = ['id' => $k, 'data' => json_decode($v, true)];
        }
        return $groupData;
    }


    public function mUpdate($type, $id, $data)
    {
        $data['value'] = json_encode($data['value']);
        return  ($this->getModel())::getDB()->where('group_data_id', $id)->where('type', $type)->update($data);
    }


    public function mDelete($type, $id)
    {
        return  ($this->getModel())::getDB()->where('type', $type)->where('group_data_id', $id)->delete();
    }


    public function mExists(string $type, int $id)
    {
        return ($this->getModel())::getDB()->where('type', $type)->where($this->getPk(), $id)->count() > 0;
    }


    public function clearGroup(int $groupId)
    {
        return  ($this->getModel())::getDB()->where('group_id', $groupId)->delete();
    }


    public function mGet($id, $type)
    {
        $data =  ($this->getModel())::getDB()->where('group_data_id', $id)->where('type', $type)->find();
        return $data ? $data['value'] : null;
    }


}